/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import object.Piece;
import object.Square;

/**
 *
 * @author XiaoLong
 */
public final class ImageUtil {

    public static ImageUtil instance;
    public Image colors[];
    private final static int COLOR_SIZE = 5;
    private final static String imagePath = "/images/";

    /**
     *
     */
    private ImageUtil() {
        colors = new Image[COLOR_SIZE];
        for (int i = 0; i < COLOR_SIZE; i++) {
            colors[i] = (getImage(imagePath + (i + 1) + ".png"));
        }
    }

    public BufferedImage getImage(String imagePath) {
        try {
            return ImageIO.read(getClass().getResource(imagePath));
        } catch (IOException e) {
            //读取图片发生异常，抛出GameException
            throw new RuntimeException("read image error");
        }
    }

    /**
     * 在界面上画一个Piece对象
     *
     * @param g
     * @param piece
     */
    public void paintPiece(Graphics g, Piece piece) {
        if (piece == null) {
            return;
        }
        for (int i = 0; i < piece.getSquares().size(); i++) {
            Square s = piece.getSquares().get(i);
            if (s.getImage() > 0) {
                g.drawImage(colors[s.getImage() - 1], s.getBeginX(), s.getBeginY(), null);
            }
        }
    }

    public static ImageUtil getInstance() {
        if (instance == null) {
            instance = new ImageUtil();
        }
        return instance;
    }
}
